import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { removeToken } from '@/utils/cookie'
import { showLoading, tryHideLoading } from './loading.js'
import Router from '@/router'
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 50000
})
// 全局加载loading方法 (请求拦截器)
service.interceptors.request.use(
  config => {
    // tryHideLoading() // 避免切换请求遮罩不消失，所以就先消失遮罩
    showLoading()
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(response => {
  const res = response.data.resultCode
  // 0000 成功 || 0001 账号已存在 || 0002 参数错误 || 0003 账号未注册
  if (res === '9999') {
    tryHideLoading()
    MessageBox.alert(
      response.data.resultMessage, '提示', {
        confirmButtonText: '确定',
        callback: action => {
          removeToken()
          Router.replace({
            path: '/login/true'
          })
        }
      }
    )
  }
  if (res === '0001') {
    tryHideLoading()
    Message.error({
      message: response.data.resultMessage,
      type: 'error'
    })
  }
  if (res === '0002') {
    tryHideLoading()
    Message.error({
      message: response.data.resultMessage,
      type: 'error'
    })
  }
  if (res === '0003') {
    tryHideLoading()
    MessageBox.alert(
      response.data.resultMessage, '提示', {
        confirmButtonText: '确定',
        callback: action => {
          removeToken()
          Router.replace({
            path: '/login/true'
          })
        }
      }
    )
  } else {
    tryHideLoading()
    return response
  }
})
export default service
